#include "entities/camera.hpp"

#include "room.hpp"

namespace nmc
{
	Camera::Camera() :
		mPlayer(NULL)
	{
	}

	Camera::~Camera()
	{
	}

	void Camera::setTarget(Player *player)
	{
		mPlayer = player;
	}

	void Camera::moveToTarget(Room *room)
	{
		if (mPlayer != NULL)
		{
			setPosition(mPlayer->getCenterX() - 160, mPlayer->getCenterY() - 140);
		}

		clampToRoomEdges(room);
	}

	void Camera::logic(Room *room)
	{
		if (mPlayer == NULL)
		{
			return;
		}

		int targetX, targetY;

		targetX = mPlayer->getCenterX() - 160;
		
		if (mPlayer->getState() == Player::GROUND 
			|| mPlayer->getJumpY() < mPlayer->getCenterY()) 
		{
			targetY = mPlayer->getCenterY() - 140;
		} 
		else 
		{			
			targetY = mPlayer->getJumpY() - 140;
		}

		if (targetY < 0)
		{
			targetY = 0;
		}

		if (targetY >= room->getHeight() - 240)
		{
			targetY = room->getHeight() - 240;
		}

		int dx = (targetX - mX) / 4;
		int dy = targetY - mY;

		if (dy < 0) 
		{
			dy /= 12;
			dy--;
		} 
		else if (dy > 0) 
		{
			dy /= 12;
			dy++;
		}
		
		mX += dx;

		if (dy < 7 && dy > -7) 
		{
			mY += dy;
		} 
		else 
		{
			if (dy < 0) 
			{
				mY -= 7;
			} 
			else 
			{
				mY += 7;
			}
		}

		clampToRoomEdges(room);
	}

	void Camera::draw(BITMAP *dest, int scrollX, int scrollY, unsigned int layer)
	{
	}

	bool Camera::isToBeDeleted()
	{
		return false;
	}

	void Camera::clampToRoomEdges(Room *room)
	{
		if (mX < 0)
		{
			mX = 0;
		}

		if (mY < 0)
		{
			mY = 0;
		}

		if (mX >= room->getWidth() - 320)
		{
			mX = room->getWidth() - 320;
		}

		if (mY >= room->getHeight() - 240)
		{
			mY = room->getHeight() - 240;
		}
	}
}